package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"golang_template/dto/requestDto"
	"golang_template/global"
	"golang_template/middlewares"
	"golang_template/model"
	"golang_template/utils"
)

type UserController struct {
}

// Register 注册用户
func (UserController) Register(c *gin.Context) {
	//没有数据表 创建数据表
	global.DB.AutoMigrate(&model.User{})
	//拿到请求映射结构体
	var userInput requestDto.LoginRequest
	//绑定结构体数据
	//逻辑判断
	if err := c.ShouldBind(&userInput); err != nil {
		c.JSON(200, gin.H{
			"code": 1,
			"msg":  "参数错误",
		})
	} else {
		fmt.Printf("%#v", userInput)
		tx, _ := model.User{}.Find(userInput.Account)
		fmt.Println(tx.RowsAffected)
		if tx.RowsAffected != 0 {
			c.JSON(200, gin.H{
				"code": 1,
				"msg":  "账号已存在",
			})
		} else {
			//账号不存在可以创建账号
			//实例化user
			var user model.User
			user.Account = userInput.Account
			//密码加密
			user.Password = middlewares.Hmac(global.Config.Md5.Key, userInput.Password)
			//调用创建
			user.Create()
			c.JSON(200, gin.H{
				"code": 0,
				"msg":  "创建成功!",
			})
		}
	}

}

func (UserController) Login(c *gin.Context) {
	var userInput requestDto.LoginRequest
	if err := c.ShouldBind(&userInput); err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "参数错误",
		})
	} else {
		if tx, user := (model.User{}).Find(userInput.Account); tx.RowsAffected == 0 {
			c.JSON(200, gin.H{
				"code": 1,
				"msg":  "账号不存在！",
			})
		} else {
			if middlewares.Hmac(global.Config.Md5.Key, userInput.Password) == user.Password {
				token, _ := middlewares.GenToken(user.Account, int(user.ID))
				c.JSON(200, gin.H{
					"code":  0,
					"msg":   "登录成功!",
					"token": token,
				})
			} else {
				c.JSON(200, gin.H{
					"code": 1,
					"msg":  "账号或密码错误",
				})
			}
		}

	}

}

func (UserController) Update(c *gin.Context) {
	value, _ := c.Get("id")

	fmt.Println(utils.ToInt(value.(string)))
}
